<template>
  <div>
    <table border='1px'>
    <tr>
        <th>
            <input v-model='checked' @change="isselect" type='checkbox'>
        </th>
        <th>商品名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>小计</th>
        <th>操作</th>    
    </tr>
    <tr v-for="product in $root.cars[shopid]" :key="product.id">
        <td><input type='checkbox' v-model='pid' :value="product.id"></td>
        <td>{{product.title}}</td>
        <td>{{product.price}}</td>
        <td>
            <button @click="carSub(product)">-</button>
            {{product.num}}
            <button @click="carAdd(product)">+</button>
        </td>
        <td>{{Math.round(product.price*product.num*100)/100}}</td>
        <td>
            <button @click="del(product.id)">X</button>
        </td>
    </tr> 
    </table>
    {{checked}}
    {{total}}<button @click="emptyCar()">清空</button>
  </div>
</template>

<script>
export default {
    props:['shopid'],
    data(){
        return{
            pid:[],
            checked:false
        };
    },
    computed:{
        total(){
            // let sum=0;
            // this.pid.forEach(id=>{
            //     sum+=this.$root.car[this.shopid][id].price*this.$root.car[this.shopid][id].num;
            // });
            // return Math.round(sum*100)/100;}
            let sum=0
            this.pid.forEach((el)=>{
                let p=this.$root.cars[this.shopid][el]
                sum+=p.num*p.price
                console.log(el)
            });
            return sum
        },
        countPid(){
            return this.pid.length;
        },
        countcars(){
            return Object.keys(this.$root.cars[this.shopid]).length;
        }
    },
    watch:{
        countpid(newval){
            if(this.countPid===this.countCars){
                this.checked=true
            }else{
                this.checked=false
            }
            newval==this.countcars;
        }
    },
    methods:{
        isselect(){
                if(this.checked){
                   this.pid= Object.keys(this.$root.cars[this.shopid])
                }else{
                    this.pid=[]
                }
        },
        carAdd(product){
            if(product.id in this.$root.cars[this.shopid]){
                if(product.num>=product.store){
                    return;
                }
                this.$root.cars[this.shopid][product.id].num++;
            }else{
                product.num=1;
                this.$set(this.$root.cars[this.shopid],product.id,product);
            }
        },
        carSub(product){
            product.num--;
            if(product.num==0){
                this.$delete(this.$root.cars[this.shopid],product.id);
            }
        },
        emptyCar(){
            this.$set(this.$root.cars,this.shopid,{});
        },
        del(id){
           this.$delete(this.$root.cars[this.shopid],id)
        }
    }
}
</script>

<style>

</style>
